package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbDict;
import com.bwie.service.TbDictService;
import com.bwie.mapper.TbDictMapper;
import com.bwie.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lenovo
 * @description 针对表【tb_dict(字典表)】的数据库操作Service实现
 * @createDate 2025-06-24 10:28:32
 */
@Service
public class TbDictServiceImpl extends ServiceImpl<TbDictMapper, TbDict>
        implements TbDictService {

    @Autowired
    TbDictMapper tbDictMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    public void loadDictList() {
        System.out.println("项目启动时，加载字典列表到缓存中");
        //key=字典类型 value=[字典列表]
        //使用redis的hasmap的数据类型
        List<TbDict> tbDictList = tbDictMapper.selectList(null);
        for (TbDict tbDict : tbDictList) {
            String key1 = "dict-" + tbDict.getDictType();
            String key2 = "" + tbDict.getDictId();
            stringRedisTemplate.opsForHash().put(key1, key2, JSON.toJSONString(tbDict));
        }
        System.out.println("加载字典列表完成");
    }

    @Override
    public Result getDictList(Integer typeId) {
        //检查缓存中是否存在
        String key1 = "dict-" + typeId;
        Boolean hasKey = stringRedisTemplate.hasKey(key1);
        if (hasKey) {
            System.out.println("从缓存中获取字典列表");
            List<Object> objectList = stringRedisTemplate.opsForHash().values(key1);
            ArrayList<TbDict> list = new ArrayList<>();
            for (Object object : objectList) {
                TbDict tbDict = JSON.parseObject(object.toString(), TbDict.class);
                list.add(tbDict);
            }
            return Result.ok().setData(list);
        }

        //缓存中不存在 从数据库获取
        System.out.println("从数据库读取字典列表");
        List<TbDict> tbDictList = tbDictMapper.selectList(
                new QueryWrapper<TbDict>().lambda().eq(TbDict::getDictType, typeId)
        );
        for (TbDict tbDict : tbDictList) {
            key1 = "dict-" + typeId;
            String key2 = "" + tbDict.getDictId();
            stringRedisTemplate.opsForHash().put(key1, key2, JSON.toJSONString(tbDict));
        }
        return Result.ok().setData(tbDictList);
    }
}




